package com.doudou.pay.helper.server.handler;

import java.io.UnsupportedEncodingException;

import com.alibaba.fastjson.JSON;
import com.doudou.pay.helper.entities.UserPay;
import com.doudou.pay.helper.server.protoco.ProtocoConsts;
import com.doudou.pay.helper.server.protoco.TcpMsg;
import com.doudou.pay.helper.server.protoco.TcpMsgBody;
import com.doudou.pay.helper.server.protoco.TcpMsgHeader;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;

public class WriteMsgHandler {
	public static boolean writePay(UserPay userPay) {
		TcpMsgHeader header = new TcpMsgHeader();
		header.setAuthToken(userPay.getAuthToken());
		header.setMsgType(ProtocoConsts.TCP_MSG_TYPE_REQUEST_PAY);
		
		TcpMsgBody tcpMsgBody = new TcpMsgBody(ProtocoConsts.SUCCESS, ProtocoConsts.SUCCESS_DEFINE);
		tcpMsgBody.setData(userPay);
		
		TcpMsg tcpMsg = new TcpMsg(header, tcpMsgBody);
		Channel channel = ChannelCacheManager.getChannel(userPay.getAuthToken());
		if(channel.isActive()) {
			try {
				
				byte[] data = msgEncode(tcpMsg);
				System.out.println("write length = " + data.length);
				ChannelFuture channelFuture = channel.writeAndFlush(Unpooled.copiedBuffer(data))
													 .sync();
				if(channelFuture.isSuccess()) {
					System.out.println("服务端写成功");
				}
				return true;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	
	public static byte[] msgEncode(TcpMsg tcpMsg) throws UnsupportedEncodingException {
		String msgText = JSON.toJSONString(tcpMsg) + "\n";
		return msgText.getBytes(ProtocoConsts.CHARSET);
	}
}
